// export default {
//   mounted(el: Element, binding: any) {
//     let [fn, debounceTime = 500, immediate = true] = binding.value; // fn：要执行的函数 防抖时间默认0.5s,
//     let timer: any;
//     el.addEventListener("click", (event: any) => {
//       timer && clearTimeout(timer);
//       if (immediate) {
//         let callNow = !timer;
//         timer = setTimeout(() => fn(), debounceTime);
//         if (callNow) {
//           fn();
//           clearTimeout(timer);
//         }
//       } else {
//         timer = setTimeout(() => fn(), debounceTime);
//       }
//     });
//   }
// };

import type { Directive, DirectiveBinding } from 'vue'

const debounce: Directive = {
  mounted (el: Element, binding: DirectiveBinding<any>) {
    const [fn, debounceTime = 500, immediate = true] = binding.value // fn：要执行的函数 防抖时间默认0.5s,
    let timer: any
    el.addEventListener('click', (event: any) => {
      timer && clearTimeout(timer)
      if (immediate) {
        const callNow = !timer
        timer = setTimeout(() => fn(), debounceTime)
        if (callNow) {
          fn()
          clearTimeout(timer)
        }
      } else {
        timer = setTimeout(() => fn(), debounceTime)
      }
    })
  }
}

export default debounce
